package com.base.monitor.module.biz.runner;

import cn.hutool.core.util.StrUtil;
import com.base.monitor.model.model.biz.collect.entity.Blacklist;
import com.base.monitor.module.biz.component.RefreshComponent;
import com.base.monitor.module.biz.context.ClientContext;
import com.base.monitor.module.biz.mq.MonitorQueueProducer;
import com.base.monitor.module.biz.properties.NetworkProperties;
import com.base.monitor.module.biz.properties.ParamProperties;
import com.base.monitor.module.biz.server.TcpServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@EnableConfigurationProperties({NetworkProperties.class, ParamProperties.class})
@Component
public class ServerStartRunner implements CommandLineRunner {

    @Autowired
    private NetworkProperties networkProperties;

    @Autowired
    private TcpServer tcpServer;

    @Value("${receive.queue.name}")
    private String queueName;

    @Autowired
    private ParamProperties paramProperties;

    @Autowired
    private MonitorQueueProducer monitorQueueProducer;

    @Autowired
    private RefreshComponent refreshComponent;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        // 1.初始化连接黑名单
        initBlackList();
        // 2.启动服务器和mq
        refreshComponent.start();
    }

    /**
     * 初始化连接黑名单
     */
    private void initBlackList() {
        String blacklistStr = networkProperties.getBlacklist();
        if (StrUtil.isBlank(blacklistStr)) {
            return;
        }
        List<String> blackListArray = new ArrayList<>(Arrays.asList(blacklistStr.split(",")));
        List<Blacklist> list = new ArrayList<>();
        for (String item : blackListArray) {
            Blacklist blacklist = new Blacklist();
            String[] split = item.split("#");
            if (split.length == 0) {
                continue;
            }
            if (split.length == 1) {
                blacklist.setCommand(split[0]);
                list.add(blacklist);
                continue;
            }
            blacklist.setCommand(split[0]);
            blacklist.setJoinTime(split[1]);
            list.add(blacklist);
        }
        ClientContext.setBlacklist(list);
    }
}
